<template>
  <editor-layout class="edit" @ok="handleOk" v-on="$listeners" v-loading="loading" :loading="saveLoading">
    <el-form class="full-form" size="small" :model="model" :rules="rule" ref="form" label-width="90px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="标题" prop="title">
            <el-input type="text" v-model="model.title" placeholder="标题" clearcbale/>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="full-editor" ref="jsonedit">

      </div>
    </el-form>
  </editor-layout>
</template>

<script>
import {postSysContentSave, postSysContentUpdate, getSysContentInfoId} from '$my/code/api/content'
import JSONEditor from 'jsoneditor'
import 'jsoneditor/dist/jsoneditor.css'

export default {
  name: 'edit-json',
  cName: 'json编辑',
  props: {
    id: String
  },
  data() {
    return {
      loading: false,
      saveLoading: false,
      model: {
        title: '',
        content: ''
      },
      rule: {
        title: [{required: true, message: '必填项'}]
      }
    }
  },
  methods: {
    async init() {
      this.initEdit()
      if (this.id) {
        this.loadForm()
      }
    },
    initEdit() {
      const container = this.$refs.jsonedit
      const editor = new JSONEditor(container, {
        mode: 'tree',
        modes: ['code', 'text', 'tree', 'preview']
      })
      editor.expandAll()
      this.editor = editor
    },
    async loadForm() {
      this.loading = true
      const data = await getSysContentInfoId(this.id).catch(e => {
        this.loading = false
        throw new Error(e)
      })
      const {id, title, content} = data
      this.model = {id, title}

      if(content) {
        let json = []
        try {
          json = JSON.parse(content)
        } catch(e) {
          json = {}
        }
        this.editor.set(json)
      }

      this.loading = false
    },
    handleOk() {
      let saveFn = postSysContentSave
      if(this.model.id) {
        saveFn = postSysContentUpdate
      }
      this.saveLoading = true

      const str = this.editor.getText()
      this.model.content = str

      saveFn({...this.model}).then(res => {
        this.saveLoading = false
        this.$notify.success('保存成功！')
        this.$emit('on-ok')

      }).catch(e => {
        console.info(e)
        this.saveLoading = false
      })
    }
  },
  mounted() {
    this.init()
  }
}
</script>

<style lang="scss" scoped>
.edit {

  .full-form {
    height: 100%;
    padding-right: 10px;
  }
  .full-editor {
    height: calc(100% - 60px);
  }
}
</style>
